﻿#region

using System;
using System.Collections.Generic;
using System.Linq;
using HouseHoldBudget.Core.Data;
using HouseHoldBudget.Core.Entities.Budgets;

#endregion

namespace HouseHoldBudget.Services.Budgets
{
    public class BudgetCategoryService : IBudgetCategoryService
    {
        #region Readonly & Static Fields

        private readonly IRepository<BudgetCategory> _budgetCategoryRepository;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="BudgetCategoryService" /> class.
        /// </summary>
        /// <param name="budgetCategoryRepository">The budget category repository.</param>
        public BudgetCategoryService(IRepository<BudgetCategory> budgetCategoryRepository)
        {
            _budgetCategoryRepository = budgetCategoryRepository;
        }

        #endregion

        #region IBudgetCategoryService Members

        /// <summary>
        /// Gets the budget categories by budget id.
        /// </summary>
        /// <param name="budgetId">The budget id.</param>
        /// <returns></returns>
        public List<BudgetCategory> GetBudgetCategoriesByBudgetId(Guid budgetId)
        {
            var query = from b in _budgetCategoryRepository.Table
                        where b.BudgetId == budgetId
                        select b;

            return query.ToList();
        }

        /// <summary>
        ///   Inserts the budget category.
        /// </summary>
        /// <param name="category"> The budget. </param>
        public void InsertBudgetCategory(BudgetCategory category)
        {
            _budgetCategoryRepository.Insert(category);
        }

        /// <summary>
        /// Updates the budget category.
        /// </summary>
        /// <param name="category">The budget.</param>
        public void UpdateBudgetCategory(BudgetCategory category)
        {
            _budgetCategoryRepository.Update(category);
        }

        /// <summary>
        /// Deletes the budget category.
        /// </summary>
        /// <param name="category">The budget.</param>
        public void DeleteBudgetCategory(BudgetCategory category)
        {
            category.ExpenseTypes.Clear(); //Remove all expense types that mapped to the category
            _budgetCategoryRepository.Delete(category);
        }

        /// <summary>
        ///   Gets the budget category.
        /// </summary>
        /// <param name="id"> The id. </param>
        /// <returns> </returns>
        public BudgetCategory GetBudgetCategory(Guid id)
        {
            return _budgetCategoryRepository.GetById(id);
        }

        #endregion
    }
}